/**   
* @{#} TableNode.java Create on 2013-8-12 下午2:16:26   
*   
* Copyright (c) 2012 by Baidu.   
*/
package objtable.engine.xmlnode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

import objtable.engine.ExeNode;
import objtable.engine.XmlEngine;
import objtable.engine.xmlnode.gen.Sqlrunner;

import objtable.port.DbPort;

/**   
* @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>  
* @version 1.0   
*/
public class SqlRunnerNode extends ExeNode {
	private static Logger log = LoggerFactory.getLogger(SqlRunnerNode.class);

	private Sqlrunner run;

	public Sqlrunner getRun() {
		return run;
	}

	public void setRun(Sqlrunner run) {
		this.run = run;
	}

	@Override
	public void exeNode() {
		if (run.getDb() != null && run.getCondition() != null
				&& run.getCondition().toLowerCase().equals("true")) {
			DbPort port = (DbPort) XmlEngine.getObjById(run.getDb());

			if (run.getSql().size() > 0) {
				log.info(run.getSql() + ":结果:" + port.runSql(run.getSql()));
			}

			if (run.getFile().size() > 0) {
				List<String> sqls = new ArrayList<String>();
				for (String f : run.getFile()) {
					try {
						List<String> ls = Files.readLines(new File(f),
								Charsets.UTF_8);
						sqls.addAll(ls);
					} catch (IOException e) {
						throw new RuntimeException("文件不存在:" + f);
					}
				}
				log.info(run.getFile() + ":结果:" + port.runSql(sqls));
			}
		}
	}
}
